package com.abc20230319.demo.controller;

import com.abc20230319.demo.entity.ChangePasswordRequest;
import com.abc20230319.demo.entity.CommonResult;
import com.abc20230319.demo.JwtTokenUtil;
import com.abc20230319.demo.entity.User;
import com.abc20230319.demo.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin-api/user/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @GetMapping("/profile/get")
    public CommonResult<?> getUserProfile(@RequestHeader("Authorization") String authHeader) {

        // 解析Authorization请求头中的JWT令牌 Bearer access_token
        String token = authHeader.substring(7);
        String username = jwtTokenUtil.getUsernameFromToken(token);

        User foundUser = userMapper.findByUsername(username);

        CommonResult<User> result = CommonResult.success(foundUser);
        return result;
    }

    @PostMapping("/changepassword")
    public CommonResult<?> changePassword(@RequestHeader("Authorization") String authHeader, @RequestBody ChangePasswordRequest body) {
        String token = authHeader.substring(7);
        User foundUser = userMapper.findByUsername(jwtTokenUtil.getUsernameFromToken(token));

        if (foundUser == null) {
            return CommonResult.error(50003, "用户不存在，修改密码失败");
        }

        if (!foundUser.getPassword().equals(body.getOldPassword())) {
            return CommonResult.error(50003, "旧密码错误");
        }

        try {
            // 执行修改密码的操作
            userMapper.changePassword(jwtTokenUtil.getUsernameFromToken(token), body.getNewPassword());
        } catch (Exception e) {
            // 处理修改失败的情况
            System.out.println(e.toString());
            return CommonResult.error(50003, "修改密码失败");
        }
        return CommonResult.success("修改密码成功");
    }
}